<script setup lang="tsx">
import { regionsListRegionApi } from '@/api/regions'
import { Province } from '@/api/regions/types'
import { businessListApi } from '@/api/merchantManagement'
import { merchantListApi } from '@/api/BusinessManagement'
import type { MerchantListParams } from '@/api/BusinessManagement/types'
import Detail from './components/Detail.vue'
import { ElButton } from 'element-plus'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useI18n } from '@/hooks/web/useI18n'
import { useTable } from '@/hooks/web/useTable'
import { useSearch } from '@/hooks/web/useSearch'
// import { MerchantStateDict } from '@/utils/dict'
// import { MerchantStateDict, CompanyTypeDict, dictToList } from '@/utils/dict'
import { useRouter } from 'vue-router'
import { hasPermission as hasPermis } from '@/components/Permission/src/utils'

const { t } = useI18n()

const { push } = useRouter()

const activeTab = ref(0)

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const res = await merchantListApi({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      state: unref(activeTab) === 0 ? '' : unref(activeTab),
      ...unref(searchParams)
    })
    return {
      list: res.data.list || [],
      total: res.data.total || 0
    }
  }
})
const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList } = tableMethods

const { searchRegister, searchMethods } = useSearch()
const { setValues } = searchMethods

const isDisabled = ref(true)
const parentId = ref(0)
const provinceList = ref<Province[]>([])
const cityList = ref<Province[]>([])

const getProvinceList = async () => {
  const res = await regionsListRegionApi(0)
  provinceList.value = res.data
  return res.data?.map((v) => ({
    label: v.localName,
    value: v.id
  }))
}

getProvinceList()

const getCityList = async (id) => {
  const res = await regionsListRegionApi(id)
  cityList.value = res.data
  return res.data?.map((v: any) => ({
    label: v.localName,
    value: v.id
  }))
}

const getBusinessList = async () => {
  if (!hasPermis('GET /business/page')) {
    allSchemas.searchSchema.at(2)!.hidden = true
    return []
  }
  const res = await businessListApi({
    pageNum: 1,
    pageSize: 9999
  })
  return res.data.list?.map((v) => ({
    label: v.businessShortName,
    value: v.id
  }))
}

const tabs = [
  {
    label: '全部',
    value: 0
  },
  {
    label: '正常',
    value: 1
  },
  {
    label: '停用',
    value: 2
  }
]

const searchRef = ref()

const tabChange = (v) => {
  searchRef.value[0].reset()
  activeTab.value = v
  currentPage.value = 1
  searchParams.value = {}
  getList()
}

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'id',
    label: '商户ID',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'merchantNo',
    label: '商户ID',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'merchantShortName',
    label: '商户简称',
    search: {
      componentProps: {
        placeholder: '请输入商户简称'
      }
    },
    form: {
      hidden: true
    },
    table: {
      width: 220,
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <div class={'flex items-center'}>
                <img class={'w-10'} src={row.avatar} />
                <span>{row.merchantShortName}</span>
              </div>
            </>
          )
        }
      }
    }
  },
  {
    field: 'hfMerchantNo',
    label: '汇付商户号',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      width: 100
    }
  },
  {
    field: 'contactName',
    label: '联系人',
    search: {
      componentProps: {
        placeholder: '请输入联系人姓名/手机号'
      }
    },
    form: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <div>{row.contactMobileNo}</div>
              <div>{row.contactName}</div>
            </>
          )
        }
      }
    }
  },
  {
    field: 'merchantName',
    label: '企业/个体工商户名称',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'provinceName',
    label: '所属省',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'cityName',
    label: '所属市',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'position',
    label: '详细地址',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  // {
  //   field: 'state',
  //   label: t('userDemo.status'),
  //   search: {
  //     hidden: true
  //   },
  //   form: {
  //     hidden: true
  //   },
  //   // search: {
  //   //   component: 'Select',
  //   //   componentProps: {
  //   //     options: dictToList(MerchantStateDict)
  //   //   }
  //   // },
  //   table: {
  //     slots: {
  //       default: (data: any) => {
  //         const row = data.row as any
  //         return (
  //           <>
  //             <span>{row.state && MerchantStateDict[row.state]}</span>
  //           </>
  //         )
  //       }
  //     }
  //   }
  // },
  // {
  //   field: 'merchantType',
  //   label: '类型',
  //   form: {
  //     hidden: true
  //   },
  //   search: {
  //     component: 'Select',
  //     componentProps: {
  //       options: dictToList(CompanyTypeDict)
  //     }
  //   },
  //   table: {
  //     slots: {
  //       default: (data: any) => {
  //         const row = data.row as any
  //         return (
  //           <>
  //             <span>{row.state && CompanyTypeDict[row.state]}</span>
  //           </>
  //         )
  //       }
  //     }
  //   }
  // },
  {
    field: 'mccName',
    label: '所属行业',
    form: {
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      width: 200
    }
  },
  // {
  //   field: 'applyTime',
  //   label: '所属商家',
  //   search: {
  //     hidden: true
  //   },
  //   form: {
  //     hidden: true
  //   },
  //   table: {
  //     width: 200
  //   }
  // },
  {
    field: 'businessId',
    label: '所属商家',
    // search: {
    //   component: 'Select',
    //   optionApi: async () => getBusinessList()
    // },
    search: {
      component: 'Select',
      optionApi: async () => getBusinessList()
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'provinceId',
    label: '省',
    search: {
      component: 'Select',
      componentProps: {
        on: {
          change: (val: number) => {
            if (val) {
              isDisabled.value = false
              parentId.value = val
              // setValue()
              setValues({
                cityId: null
              })
            } else {
              isDisabled.value = true
              setValues({
                cityId: null
              })
            }
          }
        }
      },
      optionApi: async () => getProvinceList()
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'cityId',
    label: '市',
    search: {
      component: 'Select',
      componentProps: {
        disabled: isDisabled
      },
      optionApi: async () => getCityList(parentId.value)
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'createTime',
    label: '入驻时间',
    search: {
      component: 'DatePicker',
      componentProps: {
        type: 'datetimerange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    },
    form: {
      hidden: true
    },
    table: {
      width: 220
    }
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      width: 220,
      slots: {
        default: (data: any) => {
          const row = data.row as MerchantListParams
          return (
            <>
              <ElButton
                v-hasPermi="GET /merchant/details"
                type="primary"
                link
                onClick={() => details(row)}
              >
                查看详情
              </ElButton>
              <ElButton
                v-hasPermi="GET /merchant/pageRelationBusiness"
                type="primary"
                link
                onClick={() => relation(row)}
              >
                关联商家
              </ElButton>
            </>
          )
        }
      }
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const searchParams = ref({})
const setSearchParams = (params: any) => {
  const { createTime, provinceId, cityId, ...rest } = params
  let startTime, endTime, cityName, provinceName
  if (createTime && createTime.length > 0) {
    startTime = createTime[0]
    endTime = createTime[1]
  }
  if (provinceId) {
    provinceName = provinceList.value.find((item) => item.id === provinceId)?.localName
  }
  if (cityId) {
    cityName = cityList.value.find((item) => item.id === cityId)?.localName
  }
  currentPage.value = 1
  if (Object.keys(params).length === 0) {
    isDisabled.value = true
  }
  searchParams.value = {
    startTime,
    endTime,
    cityName,
    provinceName,
    ...rest
  }
  getList()
}

const showDrawer = ref(false)

const relation = (row: any) => {
  push(`/business/detail?id=${row.id}`)
}

const detailId = ref(0)

const details = async (row: any) => {
  console.log(row)
  detailId.value = row.id
  showDrawer.value = true
}
</script>

<template>
  <div class="flex w-100% h-100%">
    <ContentWrap class="flex-[3] ml-20px">
      <ElTabs v-model="activeTab" @tab-change="tabChange">
        <ElTabPane v-for="item in tabs" :key="item.value" :label="item.label" :name="item.value">
          <Search
            ref="searchRef"
            :schema="allSchemas.searchSchema"
            @reset="setSearchParams"
            @search="setSearchParams"
            @register="searchRegister"
          />
          <Table
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :columns="allSchemas.tableColumns"
            :data="dataList"
            :loading="loading"
            @register="tableRegister"
            :pagination="{
              total
            }"
          />
        </ElTabPane>
      </ElTabs>
    </ContentWrap>

    <ElDrawer
      title="商户详情"
      v-model="showDrawer"
      direction="rtl"
      size="650px"
      @close="showDrawer = false"
    >
      <Detail v-if="showDrawer" :id="detailId" />
    </ElDrawer>
  </div>
</template>
